package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.user.pojo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: taft
 * @Date: 2018-10-25 11:44
 */
@Service
public class AuthService {

    /**
     * 通过用户名和密码去查询数据库
     * */

    @Autowired
    private UserClient userClient;

    public String accredit(String username, String password,JwtProperties jwtProperties) {
        User user = userClient.queryUser(username,password);
        //user不为空要生成token
        if (user != null) {

            UserInfo userInfo = new UserInfo();

            BeanUtils.copyProperties(user,userInfo);

            try {
                return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpire());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    public UserInfo verify(String token,JwtProperties jwtProperties) {
        try {
           return JwtUtils.getInfoFromToken(token,jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
